package pl.un4giv3n.mightvsmagic.action;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import pl.un4giv3n.mightvsmagic.entity.Action;
import pl.un4giv3n.mightvsmagic.entity.ActionType;
import pl.un4giv3n.mightvsmagic.entity.Item;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.utils.ActionUtil;
import pl.un4giv3n.mightvsmagic.utils.ImageUtil;
import pl.un4giv3n.mightvsmagic.utils.ItemUtil;

/**
 * @author andrzejewskia
 * show profile page
 */
public class ProfilePageAction extends PersistenceAction {

	private static final long serialVersionUID = 1L;
	/**
	 * session user
	 */
	private User user;

	/* (non-Javadoc)
	 * @see pl.un4giv3n.mightvsmagic.action.PersistenceAction#execute()
	 */
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		Action currentAction = user.getCurrentAction();
		if (currentAction != null
				&& currentAction.getActionType().equals(ActionType.FIGHT)) {
			if (ActionUtil.actionEnded(currentAction, user)) {
				EntityTransaction transaction = entityManager
						.getTransaction();
				transaction.begin();
				user.setCurrentAction(Action.NO_ACTION);
				entityManager.merge(user);
				entityManager.flush();
				transaction.commit();
				entityManager.close();
				return SUCCESS;
			}
		}
		entityManager.close();
		return SUCCESS;
	}
	
	/**
	 * @return list of items currently equiped by user
	 */
	public List<Item> getUserEquipedItems(){
		return ItemUtil.getUserEquipedItems(user);
	}
	/**
	 * @return list of items currently not equiped by user
	 */
	public List<Item> getUserUnequipedItems(){
		return ItemUtil.getUserUnequipedItems(user);
	}
	public String getUserAvatar(){
		return ImageUtil.getUserAvatar(user, getContext().getRealPath("/"));
	}
}
